package com.qidian.permission.service.impl;

import com.qidian.permission.entity.Permission;
import com.qidian.permission.mapper.PermissionMapper;
import com.qidian.permission.service.PermissionService;
import com.qidian.permission.util.entity.PerResult;
import org.springframework.aop.framework.AopContext;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * @Author 戴着假发的程序员
 * @Company 起点编程
 * @Time 2023/10/19 15:18
 * @Description
 */
@Service
@Transactional
public class PermissionServiceImpl implements PermissionService {
    @Autowired
    private PermissionMapper permissionMapper;

    @Transactional(propagation = Propagation.SUPPORTS,readOnly = true)
    @Override
    public PerResult selectAll() {
        // 先查询1级别类目  这里调用了一个递归查询的方法
        // 获取PermissionServiceImpl的代理对象
        PermissionService permissionService = (PermissionService) AopContext.currentProxy();
        List<Permission> permissions = permissionService.selectByParentId(0L);
        return PerResult.ok(permissions);
    }
    @Transactional(propagation = Propagation.SUPPORTS,readOnly = true)
    public List<Permission> selectByParentId(Long parentId){
        PermissionService permissionService = (PermissionService) AopContext.currentProxy();
        List<Permission> permissions = permissionMapper.selectByParentId(parentId);
        for (Permission permission : permissions){
            if(permission.getParent().equals(new Integer(2))){
                // 有子权限，递归查询
                permission.setChildren(permissionService.selectByParentId(permission.getPermissionId()));
            }
        }
        return permissions;
    }

    @Override
    public PerResult queryByUserId(Long userId) {
        return PerResult.ok(permissionMapper.queryByUserId(userId));
    }

    @Transactional(propagation = Propagation.REQUIRED)
    @Override
    public PerResult settingUserPermission(Long userId, Long[] permissionIds) {
        // 删除之前的权限
        permissionMapper.deleteRelationByUserId(userId);
        int count = permissionMapper.insertUserPermissionRelation(userId, permissionIds);
        return PerResult.ok();
    }
}
